#include <iostream>

#include <boost/shared_ptr.hpp>

#include <boost/python.hpp>
#include <boost/python/extract.hpp>
#include <boost/python/converter/registry.hpp>

namespace bp = boost::python;


int main(int argc, char* argv[])
{
   int ret_val;
   std::cout << "Starting application..." << std::flush;
   //boost::python::converter::registry::setTraceRegistry(true);

   // ---- Initialization ------ //
   // Init interpreter
   Py_Initialize();

   std::cout << "Running dir() in initial env\n";
   ret_val = PyRun_SimpleString("print dir()");

   // Retrieve the default main module and namespace
   bp::handle<> main_module( bp::borrowed(PyImport_AddModule("__main__")));
   bp::dict main_namespace;
   main_namespace = bp::dict(
                        bp::handle<>(
                                 bp::borrowed(
                                    PyModule_GetDict(main_module.get()) ) ) );

   std::cout << "Running dir on the acquired main namespace.\n";
   try
   {
      bp::handle<> r1(
         PyRun_String("import sys;     \n"
                      "import os;     \n"
                      "print ' cwd: ', os.getcwd();   \n"
                      "new_path = os.path.join(os.getcwd(),'build.linux','osg_module') \n"
                      "print ' Adding path:', new_path \n"
                      "sys.path[:0] = [new_path,]      \n"
                      "print 'path: ', sys.path        \n"
                      "print dir()                     \n",
                      Py_file_input,
                      main_namespace.ptr(), main_namespace.ptr())
      );


      bp::handle<> r2(
         PyRun_String("print 'importing osg...'  \n"
                      "import osg                \n"
                      "import time               \n",
                      Py_file_input,
                      main_namespace.ptr(), main_namespace.ptr())
      );

   //bp::str hello_mod_name("hello");
   //bp::handle<> hello_mod( PyImport_Import(hello_mod_name.ptr()) );
   //bp::handle<> hello_mod( PyImport_ImportModule("hello"));

   //bp::handle<> hello_mod( PyImport_ImportModuleEx(hello_mod_name, main_namespace.ptr(), main_namespace.ptr(), NULL ));

      std::cout << "C++: Running dir on the main namespace.\n";
      bp::handle<> r3(
         PyRun_String("print dir()     \n",
                      Py_file_input,
                       main_namespace.ptr(), main_namespace.ptr())
      );

      // Print the symbols in the main namespace


      std::cout << "\nSUCCESS: Finished everything with no exceptions or assertions. :)\n";
   }
   catch(boost::python::error_already_set)
   {
      std::cout << "Python exception:\n";
      PyErr_Print();
   }
   catch(std::exception& ex)
   {
      std::cout << "Exception: " << ex.what() << std::endl;
   }

   std::cout << "Exiting.\n" << std::endl;
   Py_Finalize();
}
